package ${package}.${subPackageName};

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.starapp.core.persistence.DynamicSpecifications;
import org.starapp.core.persistence.SearchFilter;
import ${package}.dao.${className}Dao;
import ${package}.entity.${className};

/**
 * @author ${author}
 *
 */
//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class ${className}Service {

	private ${className}Dao ${classAttrName}Dao;
	
	@Autowired
	public void set${className}Dao(${className}Dao ${classAttrName}Dao) {
		this.${classAttrName}Dao = ${classAttrName}Dao;
	}

	public ${className} get${className}(String pk) {
		return ${classAttrName}Dao.findOne(pk);
	}

	@Transactional(readOnly = false)
	public void save${className}(${className} entity) {
		${classAttrName}Dao.save(entity);
	}

	@Transactional(readOnly = false)
	public void delete${className}(String pk) {
		${classAttrName}Dao.delete(${classAttrName}Dao.findOne(pk));
	}

	public List<${className}> getAll${className}() {
		return (List<${className}>) ${classAttrName}Dao.findAll();
	}

	public Page<${className}> get${className}List(Map<String, Object> searchParams, int pageNumber, int pageSize,
			String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<${className}> spec = buildSpecification(searchParams);

		return ${classAttrName}Dao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "");
		} else if ("title".equals(sortType)) {
			sort = new Sort(Direction.ASC, "");
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<${className}> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<${className}> spec = DynamicSpecifications.bySearchFilter(filters.values(), ${className}.class);
		return spec;
	}

}


